package Thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者消费者
 */
public class ProducerAndConsumer_study {
    int index = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public static void main(String[] args) {

        ProducerAndConsumer_study producerAndConsumer = new ProducerAndConsumer_study();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                producerAndConsumer.increment();
            }
        }, "A线程 ").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                producerAndConsumer.decrement();
            }
        }, "B线程 ").start();


        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                producerAndConsumer.decrement();
            }
        }, "C线程 ").start();
    }

    //生产一个商品
    public void increment() {
        try {
            lock.lock();
            while (index != 0) {
                condition.await();
            }
            index++;
            System.out.println(Thread.currentThread().getName() + "生产一个产品,剩余产品："+index);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //生产一个商品
    public void decrement() {
        try {
            lock.lock();
            while (index == 0) {//一定要用while来判断

                //等待，不能生产
                condition.await();
            }
            index--;
            System.out.println(Thread.currentThread().getName() + "消费一个产品,剩余产品："+index);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
